<template>
	<view :style="skin" class="lease">
		<block v-if="appearObj">
			<view class="memberInfo">

				<view class="memberLeft">
					<u--image shape="circle" :src="appearObj.avatar" width="75px" height="75px"></u--image>
					<text>{{$t('lease.MemberLevel')}}:1</text>
				</view>
				<view class="memberRight">
					<view class="memberRight-content">
						<text>{{$t('lease.name')}}:</text>
						<text class="content-info">{{appearObj.nickname}}</text>
					</view>
					<view class="memberRight-content">
						<text>{{$t('lease.productID')}}:</text>
						<text class="content-info">{{appearObj.customerAccount}}</text>
					</view>
					<view class="memberRight-content">
						<text>{{$t('lease.phone')}}:</text>
						<text class="content-info">{{appearObj.phone}}</text>
					</view>
					<view class="memberRight-content">
						<text>{{$t('lease.rentalTimes')}}:</text>
						<text class="content-info">{{appearObj.rentNum}}</text>
					</view>

					<view class="memberRight-content">
						<text>{{$t('lease.lastRental')}}:</text>
						<text class="content-info">{{appearObj.lastTimeRent}}</text>
					</view>
				</view>
			</view>


			<view class="deviceInfo">
				<view class="deviceTitle">
					<view class="title">
						{{$t('lease.returnInfo')}}
					</view>
				</view>
				<view class="deviceMain">
					<view class="deviceLeft">
						<u--image shape="circle" :src="appearObj.photo" width="75px" height="75px"></u--image>
						<text>{{appearObj.productModel}}</text>
					</view>

					<view class="deviceRight">
						<view class="deviceRight-content">
							<text class="deviceRightT">{{$t('lease.productID')}}:</text>
							<text class="content-info">
								{{appearObj.productId}}
							</text>
						</view>
						<!-- <view class="deviceRight-content">
							<text class="deviceRightT">{{$t('lease.battery')}}:</text>
							<text class="content-info">{{electric}}%</text>
						</view> -->
						<block v-if="orderList.length > 0">


							<view class="deviceRight-content">
								<text class="deviceRightT">{{$t('lease.totalLight')}}:</text>
								<text class="content-info">{{orderList[0].data}}M</text>
							</view>
							<view class="deviceRight-content">
								<text class="deviceRightT">{{$t('lease.BrightLevel')}}:</text>
								<text class="content-info">{{orderList[1].data}}M</text>
							</view>
							<view class="deviceRight-content">
								<text class="deviceRightT">{{$t('lease.weakTime')}}:</text>
								<text class="content-info">{{orderList[2].data}}M</text>
							</view>
							<view class="deviceRight-content">
								<text class="deviceRightT">{{$t('lease.phoneTime')}}:</text>
								<text class="content-info">{{orderList[3].data}}M</text>
							</view>
							<view class="deviceRight-content">
								<text class="deviceRightT">{{$t('lease.PhoneChargingEnergy')}}:</text>
								<text class="content-info">{{orderList[4].data}}wh</text>
							</view>
							<view class="deviceRight-content">
								<text class="deviceRightT">{{$t('lease.lockTime')}}:</text>
								<text class="content-info">{{orderList[5].data}}M</text>
							</view>
							<view class="deviceRight-content">
								<text class="deviceRightT">{{$t('lease.batteryCapacity')}}:</text>
								<text class="content-info">{{orderList[6].data}}%</text>
							</view>
							<view class="deviceRight-content">
								<text class="deviceRightT">{{$t('lease.useTime')}}:</text>
								<text class="content-info">
									{{useTime}}H
								</text>
							</view>
						</block>
					</view>

				</view>

				<view class="confir">
					<u-button color="var(--subjectColor)" @click="handleNext(1)"> {{$t('lease.damage')}}
					</u-button>
					<u-button customStyle="margin-top: 10px;" :disabled="disableBtn" color="var(--subjectColor)"
						@click="handleNext(2)">{{$t('lease.noAbnormality')}}
					</u-button>
				</view>

				<!-- 	<view class="confir" v-else>
					<u-button color="var(--subjectColor)" disabled>等待产品双击上报
					</u-button>

				</view> -->

			</view>

		</block>

		<block v-else>
			<view class="emptyBox">
				<u-empty mode="data"></u-empty>

				<view class="btnBox">
					<u-button color="var(--subjectColor)" shape="circle" @click="isBlueOpne">{{$t('lease.return')}}</u-button>
				</view>
			</view>
		</block>

		<u-modal showCancelButton :show="modelShow" :content='content' @confirm="modelConfirm" @cancel="modelShow = false"
			confirmText="confirm" cancelText="cancel"></u-modal>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		leaNoStore,
		addLease
	} from '@/utils/sql/sqllease.js'
	import {
		addDevice,
		getDeviceTypeProductId
	} from '@/utils/sql/sqlDevice.js'
	import {
		mulDataDevice,
		pidToMAC,
		formatHexString,
		repetitionData,
		addColonEveryTwoChars,
		getNewYMDHMS
	} from '@/utils/index.js'
	import {
		addDeviceType,
		getDevModel
	} from '@/utils/sql/sqlDeviceType.js'
	import {
		adressAuthority
	} from '@/utils/jurisdiction.js'
	export default {
		data() {
			return {
				returnData: null,
				disableBtn: true,
				ble: uni.requireNativePlugin('ble'),
				appearObj: null, //上报信息
				tipsTime: null,
				src: '',
				val: 1,
				giveUser: {}, //归还用户 
				giveDevice: {}, //归还设备信息
				time: null,
				electric: 0, //电量
				useTime: 0, //使用时间
				orderList: [],
				modelShow: false,
				content: '',
				ageinProid: '',
			};
		},
		computed: {
			...mapState({
				skin: state => state.theme.skin
			})

		},
		methods: {
			modelConfirm() {
				this.sendReturn(this.ageinProid)
				this.modelShow = false
			},
			async handleReturn(deviceMAC, obj) {
				console.log(deviceMAC, obj);
				clearTimeout(this.tipsTime);
				clearInterval(this.time);
				uni.hideLoading();
				// 判断该设备是不是存在本地数据库
				let dRes = await getDeviceTypeProductId(deviceMAC);
				console.log(dRes);
				if (dRes.data == 0) {
					uni.showToast({
						title: deviceMAC + 'Does not exist under this agent',
						icon: 'none'
					})
					return false
				}

				// 查询该设备并且是租赁中的 信息
				leaNoStore(deviceMAC).then(res => {
					console.log(res);
					// 调试
					if (res.code == 0 && res.data.length > 0) {
						let len = res.data.length - 1;
						this.appearObj = res.data[len]

						if (obj) {
							this.orderList = obj.orderList;

							let eleIndex = obj.orderList.findIndex(item => item.order == 102)
							if (eleIndex > -1) {
								this.electric = obj.orderList[eleIndex].data
							} else {
								this.electric = 0
							}
						}else{
							this.electric = 0
						}


						let newDate = new Date().getTime()
						let leaseId = res.data[0].leaseId //因为leaseId是用时间戳
						console.log(newDate);
						this.useTime = parseInt((newDate - leaseId) / (1000 * 60 * 60))

						if (obj) {
							// APP根据剩余时间判断，剩余时间<解锁时间-3H，则允许还灯
							let residueIndex = obj.orderList.findIndex(item => item.order == 124)
							if (residueIndex > -1) {
								let residue = obj.orderList[residueIndex].data

								let leaseDay = this.appearObj.leaseDay
								let M = (((leaseDay - 1) * 24) + 15) * 60

								if (M - residue < 180) { //允许还灯
									this.disableBtn = false
								} else {
									uni.showToast({
										title: this.$t('lease.Timer') + parseInt(residue) + 'M',
										icon: 'none'
									})
									// 暂时先去除该限制
									// this.disableBtn = true
									this.disableBtn = false
								}
							} else {
								this.disableBtn = true
							}
						} else {
							this.disableBtn = false
						}



					} else if (res.code == 0 && res.data.length == 0) {
						this.reset()
						console.log('收到设备消息', deviceMAC);
						this.ageinProid = deviceMAC
						this.modelShow = true
						this.content = deviceMAC + 'send InStore'
					} else {
						console.log('未知状态');

					}
				})
			},
			isBlueOpne() {
				let that = this
				this.ble.isUiThreadOpenGPS(function(res) {
					console.log('接收', res.code); //-1为未开 1为已开
					if (res.code == -1) {
						uni.showToast({
							title: 'Please turn on positioning',
							icon: 'none'
						})
						return
					}

					adressAuthority().then(res => {
						console.log(res);
						// 判断蓝牙是否打开
						uni.openBluetoothAdapter({
							success() {
								that.handleBack();
							},
							fail() {
								uni.showToast({
									title: 'Bluetooth is off',
									icon: 'none'
								})
								return false
							},
						})
					})
				});
			},
			handleBack() {
				// 调试
				// let obj = {
				// 	orderList: [{
				// 			data: 630,
				// 			order: 136
				// 		},
				// 		{
				// 			data: 300,
				// 			order: 113
				// 		},
				// 		{
				// 			data: 100,
				// 			order: 115
				// 		},
				// 		{
				// 			data: 30,
				// 			order: 110
				// 		},
				// 		{
				// 			data: 7,
				// 			order: 133
				// 		},
				// 		{
				// 			data: 730,
				// 			order: 124
				// 		},
				// 		{
				// 			data: 5,
				// 			order: 102
				// 		}
				// 	]
				// }
				// this.handleReturn('239626316', obj);
				// return false
				

				clearInterval(this.time);
				this.ble.init();
				this.ble.start();
				// 搜索设备前，重置mac
				this.ble.resetMac();
				let that = this
				uni.showLoading({
					title: that.$t('lease.Waiting'),
					mask: true
				})
				this.timePopup()
				// 接收数据  群收到消息
				this.time = setInterval(() => {
					console.log('倒计时');
					that.ble.getBackData(function(res) {

						if (res.data.length > 0) {
							that.bleDate = res.data[0]
							let orderNum = parseInt(that.bleDate.msg.slice(4, 6), 16);
							console.log(orderNum, '指令');

							let result = repetitionData(res.data, 252)

							if (result && that.returnData == null) { //已经有数据上报了，不再处理
								console.log('符合', result);
								that.returnData = result
								let obj = mulDataDevice(result.msg) //处理设备返回的信息 7条命令集合
								console.log(obj);
								if (obj.keys == '8871736e867c66') { //还灯
									let mac = parseInt(result.mac.replace(/:/g, ''), 16); //将mac转为十进制
									that.handleReturn(mac, obj) //查找本地数据内容
								} else {
									// clearTimeout(that.tipsTime);
									// clearInterval(that.time);
									// uni.hideLoading();
									let mac = parseInt(result.mac.replace(/:/g, ''), 16);
									that.handleReturn(mac, '') //查找本地数据内容
									// uni.showToast({
									// 	title: 'Non-return light information',
									// 	icon: 'none'
									// })
								}
							}
							that.ble.clearData()
						}
					})

				}, 2000)
			},
			async handleNext(type) {
				clearInterval(this.time) //清除群回复
				if (type == 1) {
					uni.navigateTo({
						url: `/pages/property/faultReporting/faultReporting?appearObj=${JSON.stringify(this.appearObj)}&type=return`
					})
				} else {
					console.log(this.appearObj);

					this.sendReturn(this.appearObj.productId) //发送设备在库指令
					setTimeout(() => {
						this.updateDB(); //设备归还在库信息
					}, 1000)

				}
			},

			reset() {
				this.appearObj = null;
				this.disableBtn = true;
				this.returnData = null
				clearInterval(this.time);
				this.ble.stopSendCmd();
				this.ble.resetMac();
				this.time = null;
				this.electric = 0
				this.useTime = 0
				this.giveUser = {}
				this.giveDevice = {}
				uni.hideLoading()
			},
			timePopup() { //时间到了，取消数据监听
				clearTimeout(this.tipsTime)
				let that = this
				this.tipsTime = setTimeout(() => {

					that.reset()
					uni.showToast({
						title: that.$t('lease.DeviceNotFound'),
						icon: 'none'
					})
				}, 10000)
			},
			async updateDB() {
				
				let that = this;
				uni.showLoading({
					title: that.$t('lease.Waiting'),
					mask: true
				});
				let deviceInfo = {
					productId: this.appearObj.productId,
					stockStatus: 1,
					battery: this.electric
				}
				let resD = await addDevice(deviceInfo) //修改设备状态
				console.log(resD);
				let deviceInfoRes = await getDeviceTypeProductId(this.appearObj.productId)
				console.log(deviceInfoRes);
				let modelRes = await getDevModel(deviceInfoRes.data[0].productModel)
				let deviceType = {
					productModel: deviceInfoRes.data[0].productModel,
					tenantable: parseInt(modelRes.data[0].tenantable) + 1,
					inStore: parseInt(modelRes.data[0].inStore) + 1,
				}
				console.log(deviceType);
				await addDeviceType(deviceType) //修改品类的在库和可租的数量


				console.log(this.appearObj, this.orderList);
				let backProperty;
				if(this.orderList.length > 0){
					 backProperty = {
						workInterAll: this.orderList[0].data + '', //总亮灯时间
						threeLightInter: this.orderList[1].data + '', //三档亮灯时间
						oneNightInter: this.orderList[2].data + '', //一档亮灯时间
						phoneChInter: this.orderList[3].data + '', //手机充电时间
						usbPwo: this.orderList[4].data + '', //use放电能量
						remainTime: this.orderList[5].data + '', //剩余时间
						battery: this.orderList[6].data + '', //当前电量
					}
				}
				
				let currProp = JSON.parse(this.appearObj.currProp);
				if(this.orderList.length > 0){
					currProp.workInterAll = backProperty.workInterAll
					currProp.threeLightInter = backProperty.threeLightInter
					currProp.oneNightInter = backProperty.oneNightInter
					currProp.phoneChInter = backProperty.phoneChInter
					currProp.usbPwo = backProperty.usbPwo
					currProp.remainTime = backProperty.remainTime
					currProp.battery = backProperty.battery
				}
				
				let backobj = {
					leaseId: this.appearObj.leaseId,
					backDtos: JSON.stringify({
						createTime: getNewYMDHMS(),
						backProperty: backProperty
					}),
					currProp: JSON.stringify(currProp),
					leaseStatus: 1,
					iSync: 0,
					expirationTime: null
				}
				console.log(backobj);

				// 租赁列表 租赁状态转为归还状态

				let res = await addLease(backobj) //修改租赁状态
				console.log(res);
				uni.hideLoading()
				uni.showToast({
					title: that.$t('lease.ReturnSuccessful'),
					icon: 'none'
				});
				that.reset();
				// 更新产品推荐的 设备 和可租的数量
				this.$emit('updateDeviceType')


			},
			// 发送还灯指令
			sendReturn(productId) {

				let that = this
				// 发送的命令mac反转,返回的数据不需要反转

				let deviceMAC = pidToMAC(productId) //产品的PID转为设备MAC地址 转16进制 不足12位，前面0补
				let deviceMAC16 = formatHexString(deviceMAC) //反转并且加上:
				console.log(deviceMAC, deviceMAC16);
				let codeOrder = (203).toString(16)
				let code = codeOrder + deviceMAC16 + '00'

				let char = addColonEveryTwoChars(deviceMAC)
				console.log(char, code);
				this.ble.sendCmd(code, 3, char)
				setTimeout(() => {
					that.ble.stopSendCmd()
				}, 1000)
			},

		},
		mounted() {
			let that = this
			uni.$on('changeSwitch', function(data) {
				console.log('切换SwitchTab');
				that.ble.init();
				that.appearObj = null;
			})
			this.ble.init();

			this.appearObj = null;
			//页面一进入触发
			this.isBlueOpne();
			uni.$on('update_malList', function(data) {
				console.log('getMalList');
				that.reset();
			})

		},
	}
</script>

<style lang="scss" scoped>
	.lease {
		padding: 16px;
		width: 100%;
		box-sizing: border-box;
		overflow-y: auto;
		height: calc(100% - 42px);

		.emptyBox {
			width: 100%;
			height: 100%;
			box-sizing: border-box;
			border: 1px solid #ccc;
			margin-bottom: 6px;
			padding: 16px;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			flex-direction: column;
			justify-content: space-evenly;

			.btnBox {
				width: 200px;
			}
		}

		.memberInfo {
			width: 100%;
			height: 174px;
			box-sizing: border-box;
			background-color: #D7D7D7;
			margin-bottom: 6px;
			display: flex;


			.memberLeft {
				width: 94px;
				height: calc(100% - 16px);
				margin-top: 8px;
				border-right: 1px solid #ccc;
				display: flex;
				align-items: center;
				flex-direction: column;
				justify-content: center;

				text {
					margin-top: 8px;
					color: #101010;
					font-size: 12px;
				}
			}

			.memberRight {
				width: calc(100% - 94px);
				padding: 16px;
				box-sizing: border-box;
				font-size: 12px;
				color: #101010;

				.memberRight-content {
					margin-bottom: 8px;

					.content-info {
						margin-left: 8px;

					}
				}
			}
		}

		.deviceInfo {
			width: 100%;
			height: 470px;
			border: 1px solid #ccc;
			box-sizing: border-box;
			margin-bottom: 12px;
			background-color: #fff;

			.deviceTitle {
				width: calc(100% - 20px);
				height: 48px;
				background-color: #B886F8;
				margin: 10px auto;
				border-radius: 8px;
				display: flex;
				align-items: center;
				justify-content: space-evenly;


				.title {
					font-size: 20px;
					color: #fff;
				}
			}

			.deviceMain {
				display: flex;

				.deviceLeft {
					width: 94px;
					height: 320px;
					margin-top: 8px;
					border-right: 1px solid #ccc;
					display: flex;
					align-items: center;
					flex-direction: column;
					justify-content: center;
				}

				.deviceRight {
					width: calc(100% - 94px);
					padding: 8px 16px 0;
					box-sizing: border-box;
					font-size: 14px;
					color: #101010;


					.deviceRight-content {
						margin-bottom: 4px;
						display: flex;
						align-items: center;

						.deviceRightT {
							width: 320px;
							line-height: 28px;
							display: inline-block;
						}

						.content-info {
							width: 220px;
							margin-left: 8px;
							display: inline-block;

							.loadingBox {
								font-size: 20px;
								font-weight: 600;
							}

							.iconContent {
								float: right;
							}
						}

						.discounts {
							display: inline-block;
							border-bottom: 1px solid #ccc;
						}
					}

				}
			}

			.confir {
				width: calc(100% - 32px);
				margin: 0 auto;
				height: 48px;
				// display: flex;
				// align-items: center;
				// justify-content: space-evenly;
				// flex-direction: column;
			}


		}
	}
</style>